<template>
  <div class="app-container" v-loading="loading" element-loading-text="数据加载中..." element-loading-spinner="el-icon-loading"
  element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="block">
      <span class="demonstration">自动刷新频率(秒)</span>
      <el-slider v-model="refresh" :step="5" show-stops @change="updateRefresh"></el-slider>
    </div>

    <div  class="flow">
      <div ref="chartPacketCount" style="width: 450px; height: 350px;"></div>
      <div ref="chartByteCount" style="width: 450px; height: 350px;"></div>
      <div ref="chartFlowCount" style="width: 450px; height: 350px;"></div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: "Flow",
  data() {
    return {
      switchList: [],
      switchListInfo: [],
      loading: true,
      refresh: parseInt(localStorage.getItem('refresh')) || 30, // 从 localStorage 恢复刷新频率
      timer: null
    };
  },
  async created() {
    this.startRefreshTimer(); // 启动定时器
    await this.fetchData();
  },
  beforeDestroy() {
    this.clearRefreshTimer(); // 清除定时器
  },
  methods: {
    async fetchData() {
      try {
        const switchesRes = await axios.get('/ryu/stats/switches', {
          headers: {
            'Access-Control-Allow-Origin': '*'
          }
        });
        this.switchList = switchesRes.data;

        const newSwitchListInfo = []; // 用于存储新的数据
        for (let dpid of this.switchList) {
          const aggregateFlowRes = await axios.get(`/ryu/stats/aggregateflow/${dpid}`, {
            headers: {
              'Access-Control-Allow-Origin': '*'
            }
          });

          const descRes = await axios.get(`/ryu/stats/desc/${dpid}`, {
            headers: {
              'Access-Control-Allow-Origin': '*'
            }
          });

          const aggregateFlowData = Object.values(aggregateFlowRes.data)[0][0]; // 获取内部对象
          const descData = Object.values(descRes.data)[0]; // 获取内部对象

          const mergedData = {
            packet_count: aggregateFlowData.packet_count,
            byte_count: aggregateFlowData.byte_count,
            flow_count: aggregateFlowData.flow_count,
            mfr_desc: descData.mfr_desc,
            hw_desc: descData.hw_desc,
            sw_desc: descData.sw_desc,
            serial_num: descData.serial_num,
            dp_desc: descData.dp_desc,
            dpid: dpid
          };

          newSwitchListInfo.push(mergedData);
        }

        // 保留最新的数据
        this.switchListInfo = newSwitchListInfo;

        this.loading = false;
        await this.$message({
          message: '数据加载完成',
          type: 'success'
        });
        this.initCharts();
      } catch (error) {
        console.error(error);
      }
    },
    initCharts() {
      this.initChartPacketCount();
      this.initChartByteCount();
      this.initChartFlowCount();
    },
    initChartPacketCount() {
      const chart = echarts.init(this.$refs.chartPacketCount);
      const option = {
        title: { text: '数据包计数', left: 'center' },
        tooltip: {},
        xAxis: { data: this.switchListInfo.map(item => item.dp_desc), name: '', nameLocation: 'middle', nameGap: 40 },
        yAxis: { nameLocation: 'middle', nameGap: 40, axisLabel: { formatter: '{value}' } },
        series: [{ type: 'bar', data: this.switchListInfo.map(item => item.packet_count), color: '#2f4554', label: { normal: { show: true, position: 'top' } } }]
      };
      chart.setOption(option);
    },
    initChartByteCount() {
      const chart = echarts.init(this.$refs.chartByteCount);
      const option = {
        title: { text: '字节计数', left: 'center' },
        tooltip: {},
        xAxis: { data: this.switchListInfo.map(item => item.dp_desc), name: '', nameLocation: 'middle', nameGap: 40 },
        yAxis: { nameLocation: 'middle', nameGap: 40, axisLabel: { formatter: '{value}' } },
        series: [{ type: 'bar', data: this.switchListInfo.map(item => item.byte_count), color: '#5793f3', label: { normal: { show: true, position: 'top' } } }]
      };
      chart.setOption(option);
    },
    initChartFlowCount() {
      const chart = echarts.init(this.$refs.chartFlowCount);
      const option = {
        title: { text: '流计数', left: 'center' },
        tooltip: {},
        xAxis: { data: this.switchListInfo.map(item => item.dp_desc), name: '', nameLocation: 'middle', nameGap: 40 },
        yAxis: { nameLocation: 'middle', nameGap: 40, axisLabel: { formatter: '{value}' } },
        series: [{ type: 'bar', data: this.switchListInfo.map(item => item.flow_count), color: '#d14a61', label: { normal: { show: true, position: 'top' } } }]
      };
      chart.setOption(option);
    },
    startRefreshTimer() {
      this.clearRefreshTimer(); // 先清除旧的定时器
      if (this.refresh > 0) {
        this.timer = setInterval(() => {
          this.fetchData(); // 刷新数据
        }, this.refresh * 1000); // 转换为毫秒
      }
    },
    clearRefreshTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    updateRefresh(value) {
      localStorage.setItem('refresh', value); // 保存新的刷新频率到 localStorage
      this.startRefreshTimer(); // 重新设置定时器
    }
  }
};
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: Arial, sans-serif;
  background-color: white;
}

.flow {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 910px;
  /* 2个图表宽度总和加上间隙 */
  height: auto;
  /* 高度根据图表高度自适应 */
  margin-top: 30px;
}

.flow > div {
  width: 450px;
  height: 350px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.flow > :nth-child(2n) {
  margin-right: 0;
  /* 使偶数位置的元素没有右边距 */
}

.flow > :nth-last-child(-n+2) {
  margin-bottom: 0;
  /* 最后两个元素没有底边距 */
}

.block {
  width: 800px;
}

.demonstration {
  color: #F56C6C;
  font-size: 30px;
  font-weight: 800;
}
</style>